/* 
 * Copyright (c) 2012 Aalto University and University of Helsinki
 * MIT License
 * see LICENSE.txt for more information
 */

function customAutocomplete() {
    $.ui.autocomplete.prototype._renderItem = function (ul, item) {
        var label = item.label;
        var vocab = '';
        if (label.indexOf('@') != -1) {
          vocab = label.substring(label.indexOf('@'), label.length);
          item.label = label.substring(0, label.indexOf('@')); 
        }
        var output = item.label + '<span class="autocomplete-vocab">' + vocab + '</span>';
        return $("<li>")
            .append($("<a>").html(output))
            .appendTo(ul);
    };
}

$(function() { // DOCUMENT READY
  
  /*
   * Moving the sidenav scrollbar towards the current concept.
   */
  $(document).ajaxComplete(function(event, xhr, settings) {
    if (settings.url.indexOf('hierarchy') !== -1)
      $('.nav').scrollTop($('#jstree-leaf-proper')[0].offsetTop-162);
  });

  // if on the search results page and there is only one result 
  if ($('.uri-input-box').html() && $('.search-results-property-table').length === 2) { 
    invokeParentTree(getTreeConfiguration()); 
  }

  // if we are on the vocab front page initialize the hierarchy view with a top concept.
  $('#hier-trigger').click(function () {
    if($('.uri-input-box').length === 0) { // if on the vocabulary front page
      $('.active').removeClass('active');
      $('#hier-trigger').parent().addClass('active');
      var $content = $('.side-nav');
      $content.empty();
      $content.append('<div class="hierarchy-bar-tree"></div>');
      invokeParentTree(getTreeConfiguration(true)); 
      $('#hier-trigger').attr('href', '#');
      return false;
    }
    var uri = $('.uri-input-box').html();
    var redirectUrl = 'http://' + base_url + vocab + '/' + lang + '/page/' + uri.split('/')[uri.split('/').length-1];
    window.location.replace(encodeURI(redirectUrl));
  });

  var textColor = $('.search-parameter-highlight').css('color');

  if(parts.indexOf('search') == -1) { // Disabled if on the search results page.
  /*
   * Event handler for clicking the preflabel and making a selection of it for copy pasting.
   */
    $(document).on('click','.prefLabel',
      function() {
        var text = $('.prefLabel')[0];    
        var range;
        if (document.body.createTextRange) { // ms
          range = document.body.createTextRange();
          range.moveToElementText(text);
          range.select();
        } else if (window.getSelection) { // moz, opera, webkit
          var selection = window.getSelection();            
          range = document.createRange();
          range.selectNodeContents(text);
          selection.removeAllRanges();
          selection.addRange(range);
        }
        return false;
      }
      );
    
    $(document).on('click','.uri-input-box',
      function() {
        var text = $('.uri-input-box')[0];    
        var range;
        if (document.body.createTextRange) { // ms
          range = document.body.createTextRange();
          range.moveToElementText(text);
          range.select();
        } else if (window.getSelection) { // moz, opera, webkit
          var selection = window.getSelection();            
          range = document.createRange();
          range.selectNodeContents(text);
          selection.removeAllRanges();
          selection.addRange(range);
        }
        return false;
      }
      );
  }

  // Event handler for restoring the DOM back to normal after the focus is lost.
  $(':not(.search-parameter-highlight)').click(
      function(){
        $('#temp-textarea').remove();
        $('.search-parameter-highlight').css({'background': 'transparent', 'color': textColor});
      }
  );
 
  // event handling the breadcrumb expansion
  $(document).on('click', '.expand-crumbs',
      function(event){
        var clicked = $(event.currentTarget);
        clicked.parent().find('.hidden-breadcrumb').removeClass('hidden-breadcrumb').addClass('bread-crumb');
        clicked.next().remove(); // Removing and the following > symbol.
        clicked.remove(); // and the clickable '...' element
        return false;
      }
  );
  
  // event handler for clicking the hierarchy concepts
  $(document).on('click', '.jstree-no-icons a',
      function(event) {
        event.preventDefault();
        var base_path = path_fix.length / 3;
        var clicked = $(this);
        var $content = $('#page-wrapper');
        var targetUrl = 'http://' + base_url + vocab + '/' + lang + '/page/';
        var parameters = $.param({'uri' : event.target.href, 'base_path' : base_path});
        $('#hier-trigger').attr('href', targetUrl + '?uri=' + event.target.href);
        $.ajax({
            url : targetUrl,
            data: parameters,
            success : function(data) {
              $('#jstree-leaf-proper').attr('id', '');
              clicked.attr('id', 'jstree-leaf-proper');
              $content.empty();
              var title = $(data).filter('title').text();
              var response = $('#page-wrapper', data).html();
              document.title = title;
              window.history.pushState(null, null, encodeURI(targetUrl + '?uri=' + event.target.href));
              $content.append(response);
            }
        });
        return false;
      }
  );
  
  // event handler for clicking the alphabetical index concepts
  $(document).on('click', '.alphabetical-search-results a',
      function(event) {
        var base_path = path_fix.length / 3;
        var clicked = $(this);
        $('.activated-concept').removeClass('activated-concept');
        clicked.addClass('activated-concept');
        var $content = $('#page-wrapper');
        var targetUrl = event.target.href;
        var parameters = $.param({'base_path' : base_path});
        $('#hier-trigger').attr('href', event.target.href);
        $.ajax({
            url : targetUrl,
            data: parameters,
            success : function(data) {
              $content.empty();
              var title = $(data).filter('title').text();
              var response = $('#page-wrapper', data).html();
              document.title = title;
              window.history.pushState(null, null, encodeURI(event.target.href));
              $content.append(response);
            }
        });
        return false;
      }
  );
  
  // event handler for clicking the alphabetical index tab 
  $(document).on('click', '.nav-tabs a[href$="index"]',
      function(event) {
        var base_path = path_fix.length / 3;
        $('.active').removeClass('active');
        var clicked = $(this);
        clicked.parent().addClass('active');
        var $content = $('.side-nav');
        var targetUrl = event.target.href;
        var parameters = $.param({'base_path' : base_path});
        $.ajax({
            url : targetUrl,
            data: parameters,
            success : function(data) {
              $content.empty();
              var title = $(data).filter('title').text();
              var response = $('.side-nav', data).html();
              $content.append(response);
              $('.nav').scrollTop(0);
              window.history.pushState(null, null, encodeURI(event.target.href));
              document.title = title;
            }
        });
        return false;
      }
  );
  
  // event handler for the alphabetical index letters
  $(document).on('click','.pagination > li > a',
      function(event) {
        var base_path = path_fix.length / 3;
        var clicked = $(this);
        var $content = $('.side-nav');
        var base = document.baseURI;
        var targetUrl = event.target.href;
        var parameters = $.param({'base_path' : base_path});
        $.ajax({
            url : targetUrl,
            data: parameters,
            success : function(data) {
              $content.empty();
              var title = $(data).filter('title').text();
              var response = $('.side-nav', data).html();
              $content.append(response);
              $('.nav').scrollTop(0);
              window.history.pushState(null, null, encodeURI(event.target.href));
              document.title = title;
            }
        });
        return false;
      }
  );


  // sets the language cookie for 365 days
  function setLangCookie(lang) {
    createCookie('ONKI_LANGUAGE', lang, 365);
  }

  // Event handlers for the language selection links for setting the cookie
  $('#language-fi').click(function() { setLangCookie('fi'); });
  $('#language-sv').click(function() { setLangCookie('sv'); });
  $('#language-en').click(function() { setLangCookie('en'); });
  
  // Setting the language parameters according to the cookie if found.
  var search_lang = readCookie('ONKI_SEARCH_LANG');
  
  // taking the url parameters given by the controller 
  // into parts used for determining if we are on the search listings
  parts = parts.split('/'); // splits pathname, e.g.
  
  var rest_url = rest_base_url; 
  if (rest_url.indexOf('..') == -1 && rest_url.indexOf('http') == -1) { rest_url = encodeURI(location.protocol + '//' + rest_url); }
  
  // qlang is used in REST queries as a parameter. it is either
  // - "&lang=<code>" when searching in a specific language
  // - "" when searching in all languages
  var qlang = lang;
  
  // setting the focus to the search box on default
  $("#search-vocab-parameter").focus();

  if (search_lang === 'anything' || !search_lang || (typeof getUrlParams().lang !== 'undefined' && getUrlParams().lang === '')) {
    $('#lang-dropdown-toggle').html($('.lang-button-all').html() + ' <span class="caret"></span>');
    $('#lang-input').val('');
    qlang = "";
  } else {
    var langPretty = $('a[hreflang=' + search_lang + ']').html();
    if (!langPretty)
      langPretty = $('a[hreflang="anything"]').html();
    $('#lang-dropdown-toggle').html(langPretty + ' <span class="caret"></span>');
    $('#lang-input').val(search_lang);
  }
  
  $('.lang-button').click(function() {
    qlang = $(this)[0].attributes.hreflang.value;
    if (qlang === '')
      qlang = 'anything';
    $('#lang-dropdown-toggle').html($(this).html() + ' <span class="caret"></span>');
    $('#lang-input').val(qlang);
    createCookie('ONKI_SEARCH_LANG', qlang, 365);
  });
  
  $('.lang-button-all').on('click', function() {
    qlang = "";
    createCookie('ONKI_SEARCH_LANG', 'anything', 365);
    $('#lang-input').val('');
    $('#lang-dropdown-toggle').html($('.lang-button-all').html() + ' <span class="caret"></span>');
  });

  $('.lang-button, .lang-button-all').click(function() {
    $('#search-vocab-parameter').focus();
  });
  
  var searchTerm = "";
  // calls for another function to highlight search term in the labels.
  if (getUrlParams().q) {
    localSearchHighlight(decodeURI(getUrlParams().q.replace(/\*/g, '')));
    searchTerm = getUrlParams().q;
  }
  
  var NoResultsLabel = [ {
    "label" : noResultsTranslation,
    "vocab" : ""
  } ];
 
  // disables the button with an empty search form 
  $('#search-vocab-parameter').keyup(function() {
    var empty = false;
    $('#search-vocab-parameter').each(function() {
      if ($(this).val().length === 0) {
        empty = true;
      }
    });

    if (empty) {
      $('#search-all-button').attr('disabled', 'disabled');
    } else {
      $('#search-all-button').attr('disabled', false);
    }
  });
  
  // activates jquery autocomplete for the search fields
  var autoC = $("#search-vocab-parameter")
  .autocomplete(
  {
    source : function(request, response) {
      // default to prefix search when no wildcards were used
      var term = request.term.trim(); // surrounding whitespace is not significant
      term = term.indexOf("*") >= 0 ? term : term + "*";
      var parameters = $.param({'query' : term, 'vocab' : vocab, 'lang' : qlang});
      $
      .ajax({
        url : rest_url + 'search',
        data: parameters,
        dataType : "json",
        success : function(data) {
          if (data.results.length === 0) {
            response(NoResultsLabel);
          }
          else {
            response($
              .map(
                data.results
                .filter(function(item) {
                  // either we are performing a local search
                  // or the concept is native to the vocabulary
                  return (vocab !== "" || !item.exvocab);
                }),
                function(item) {
                  var name = (item.altLabel ? item.altLabel +
                    " \u2192 " +
                    item.prefLabel : item.prefLabel);
                  if(item.hiddenLabel) 
                    name =  item.hiddenLabel + " \u2192 " + item.prefLabel;
                  item.label = name;
                  if (item.vocab && item.vocab != vocab) // if performing global search include vocabid
                    item.label += ' @' + item.vocab + ' ';
                  if (item.exvocab && item.exvocab != vocab)
                    item.label += ' @' + item.exvocab + ' ';
                  if (item.lang && item.lang !== lang) // if the label is not in the ui lang
                    item.label += ' @ ' + item.lang;
                  return item;
                }));
          }
        }
      });
    },
    delay : autocomplete_delay, // time (in milliseconds)
    // before autocomplete
    // activates i.e. sends a
    // request to the REST
    // interface
    minLength : autocomplete_activation,
    appendTo: "#header-bar-content",

    select : function(event, ui) { // what happens when
      // user clicks/uses autocomplete
      var localname = ui.item.localname;
      if (ui.item.exvocab) {
        localname = "?uri=" + ui.item.uri;
      }
      if (ui.item.label === NoResultsLabel[0].label) {
        event.preventDefault();
        return false;
      }
      // replaced complex logic with path_fix that should always work.
      if (ui.item.type && ui.item.type.indexOf('Collection') !== -1) {
        location.href = encodeURI(path_fix + ui.item.vocab + '/' + lang + '/collections/' + localname);
      } else {
        location.href = encodeURI(path_fix + ui.item.vocab + '/' + lang + '/page/' + localname);
      }
    },
    focus : function(event, ui) {
      return false; // Prevent the widget from inserting the value.
    }
  }).bind('focus', function() {
    $('#search-vocab-parameter').autocomplete('search'); 
  });

  $("button#send-feedback").button({
    icons : {
      primary : "ui-icon-mail-closed"
    }
  });


  // Some form validation for the feedback form
  $("#send-feedback")
  .click(
    function() {
      $(".error").remove();
      var emailMessageVal = $("#message").val();
        
      if (emailMessageVal === '') {
        $("#message")
        .after(
          '<ul class="error"><li><span class="errors">Value is required and can\'t be empty</ul></li></span>');
        return false;
      }
      return true;
    });

  // activation and initialisation for the jquery waypoints plug-in used for
  // the scrollable search results.
  var $loading = $("<div class='col-lg-10'><h4>" + loading_text + "&hellip;<span class='spinner'/></h4></div>"), $footer = $('footer'), opts = {
    offset : '100%'
  };
  var currentlyLoading = false;
  var offcount = 1;
  var number_of_hits = document.getElementsByClassName("concept-info").length;
  var $ready = $("<div class='col-lg-10'><h4>" + results + " " + number_of_hits + " " + results_disp +"</p></h4>");
  
  if (parts[parts.length-1].indexOf('search') !== -1 && number_of_hits !== 0) { // if we are in the search page with some results
    if (number_of_hits < waypoint_results * offcount) { 
      $('#vocab-content').append($ready);
    }
    else {
      $footer.waypoint(function(event, direction) {
        if (currentlyLoading === false) {
          currentlyLoading = true;
          $footer.waypoint('remove');
          if (number_of_hits >= waypoint_results * offcount)
            $('#vocab-content').append($loading);

          var parameters = $.param({'q' : searchTerm, 'offset' : offcount * waypoint_results, 'lang' : getUrlParams().lang});
          $.ajax({
            url : window.location.pathname,
            data : parameters,
            success : function(data) {
              currentlyLoading = false;
              $loading.detach();
              if (data === '') {
                $('#vocab-content').append($ready);
                return false;
              }
              $('#vocab-content').append(data);
              $footer.waypoint(opts);
              number_of_hits = $('.uri-input-box').length;
              $ready = $("<div class='col-lg-10'><h4>" + results + " " + document.getElementsByClassName("concept-info").length + " " + results_disp +"</h4></div>");
              offcount++;
              if (getUrlParams().q) {
                localSearchHighlight(decodeURI(getUrlParams().q.replace(/\*/g, "")));
              }
              if (number_of_hits < waypoint_results * offcount) {
                $('#vocab-content').append($ready);
                currentlyLoading = true; // fixes problem where the script wouldn't realize that it had already displayed all the results
              }
              return false;
            }
          });
        }
      }, opts);
    }
  }
  customAutocomplete(); 
});
